package etcd

import (
	"gitee.com/xiedongji/antgo/cpts/xlog"
	"gitee.com/xiedongji/antgo/helper/xdebug"
	clientv3 "go.etcd.io/etcd/client/v3"
	"time"
)

/* ============================================================ *
 * 功能: redis
 * 配置：yaml
 * # etcd相关配置
 * ============================================================ */
const cptName = "etcd"

var _client *clientv3.Client

type Instance struct {
	Endpoints   []string `yaml:"endpoints"`
	DialTimeout int      `yaml:"dial_timeout"`
}

func (t *Instance) GetName() string {
	return cptName
}

func (t *Instance) Run() (err error) {
	xdebug.Dump(t)
	// 连接ETCD配置
	config := clientv3.Config{
		Endpoints:   t.Endpoints,
		DialTimeout: time.Duration(t.DialTimeout) * time.Second,
	}

	// 建立连接
	if _client, err = clientv3.New(config); err != nil {
		return
	}

	return nil
}

// ====================== 业务板块 ======================
func GetEtcdClient() *clientv3.Client {
	if _client == nil {
		xlog.Logger(cptName, "ETCD").Info().Msg("获取etcd client 为空")
	}

	return _client
}

func GetEtcdClientKV() clientv3.KV {
	return clientv3.NewKV(GetEtcdClient())
}

func GetEtcdClientLease() clientv3.Lease {
	return clientv3.Lease(GetEtcdClient())
}
